/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mfgrep;

import java.io.File;
import java.util.Iterator;
import java.util.logging.Logger;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;

/**
 * The "product".
 * 
 * Class is NOT thread safe!
 * 
 * @author lzapletal
 */
public class Main {

  private static Logger logger = Logger.getAnonymousLogger();
  private final static String DEFAULT_EXTENSIONS = "jar,sar,war,ear";

  private static void process(String[] args) throws ProcessingException {
	ProgramOptions programOptions = new ProgramOptions();
	CommandLineParser parser = new PosixParser();
	Options options = new Options();
	options.addOption("nr", false, "Do NOT recurse into directories.");
	options.addOption("cs", false, "Case SENSITIVE search.");
	options.addOption("ex", false, "Extensions to look into separated by commas (default: " + DEFAULT_EXTENSIONS + ").");
	options.addOption("li", false, "Shows LICENSE information.");
	HelpFormatter formatter = new HelpFormatter();
	CommandLine line = null;
	try {
	  line = parser.parse(options, args);
	} catch (ParseException ex) {
	  throw new ProcessingException("Cannot parse options", ex);
	}
	if (line == null || line.getArgList().size() < 2) {
	  System.err.println("Unknown parameter, file or directory not provieded");
	  formatter.printHelp("java -jar mfgrep.jar PATTERN FILE1 [FILE2] [DIR1] ...", options);
	  return;
	}

	if (line.hasOption("li")) {
	  System.out.println("(c) Lukas Zapletal, licensed under Apache Software License 2.0");
	}
	if (line.hasOption("cs")) {
	  programOptions.setCaseSensitive(true);
	} else {
	  programOptions.setCaseSensitive(false);
	}
	if (line.hasOption("nr")) {
	  programOptions.setRecurse(false);
	} else {
	  programOptions.setRecurse(true);
	}
	if (line.hasOption("ex")) {
	  String exs = line.getOptionValue("ex");
	  programOptions.setExtensions(exs);
	} else {
	  programOptions.setExtensions(DEFAULT_EXTENSIONS);
	}
	String pattern = line.getArgs()[0];
	Grepper grepper = new Grepper(pattern, programOptions);
	Iterator argsIter = line.getArgList().subList(1, line.getArgList().size()).iterator();
	while (argsIter.hasNext()) {
	  File file = new File((String) argsIter.next());
	  if (!file.exists()) {
		throw new ProcessingException("File or directory " + file + " does not exist.");
	  }
	  if (!file.canRead()) {
		throw new ProcessingException("Cannot read from file or directory " + file);
	  }
	  if (file.isDirectory()) {
		if (programOptions.isRecurse()) {
		  logger.fine("Processing directory " + file);
		  DirWalker walker = new DirWalker(file, grepper, programOptions);
		  walker.walk();
		} else {
		  logger.finer("Skipping directory (recurse disabled) " + file);
		}
	  } else if (file.isFile()) {
		grepper.acceptFile(file);
	  }
	}
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
	try {
	  process(args);
	} catch (Throwable t) {
	  logger.throwing("Main", "main", t);
	  String subcause = "";
	  if (t.getCause() != null) {
		subcause = ", " + t.getCause().getMessage();
	  }
	  logger.severe("Error occured, terminating. Cause: " + t.getMessage() + subcause);
	}
  }
}
